{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Zero-Shot Prompting Tutorial\n",
    "\n",
    "## Overview\n",
    "\n",
    "This tutorial provides a comprehensive introduction to zero-shot prompting, a powerful technique in prompt engineering that allows language models to perform tasks without specific examples or prior training. We'll explore how to design effective zero-shot prompts and implement strategies using OpenAI's GPT models and the LangChain library.\n",
    "\n",
    "## Motivation\n",
    "\n",
    "Zero-shot prompting is crucial in modern AI applications as it enables language models to generalize to new tasks without the need for task-specific training data or fine-tuning. This capability significantly enhances the flexibility and applicability of AI systems, allowing them to adapt to a wide range of scenarios and user needs with minimal setup.\n",
    "\n",
    "## Key Components\n",
    "\n",
    "1. **Understanding Zero-Shot Learning**: An introduction to the concept and its importance in AI.\n",
    "2. **Prompt Design Principles**: Techniques for crafting effective zero-shot prompts.\n",
    "3. **Task Framing**: Methods to frame various tasks for zero-shot performance.\n",
    "4. **OpenAI Integration**: Using OpenAI's GPT models for zero-shot tasks.\n",
    "5. **LangChain Implementation**: Leveraging LangChain for structured zero-shot prompting.\n",
    "\n",
    "## Method Details\n",
    "\n",
    "The tutorial will cover several methods for implementing zero-shot prompting:\n",
    "\n",
    "1. **Direct Task Specification**: Crafting prompts that clearly define the task without examples.\n",
    "2. **Role-Based Prompting**: Assigning specific roles to the AI to guide its responses.\n",
    "3. **Format Specification**: Providing output format guidelines in the prompt.\n",
    "4. **Multi-step Reasoning**: Breaking down complex tasks into simpler zero-shot steps.\n",
    "5. **Comparative Analysis**: Evaluating different zero-shot prompt structures for the same task.\n",
    "\n",
    "Throughout the tutorial, we'll use Python code with OpenAI and LangChain to demonstrate these techniques practically.\n",
    "\n",
    "## Conclusion\n",
    "\n",
    "By the end of this tutorial, learners will have gained:\n",
    "\n",
    "1. A solid understanding of zero-shot prompting and its applications.\n",
    "2. Practical skills in designing effective zero-shot prompts for various tasks.\n",
    "3. Experience in implementing zero-shot techniques using OpenAI and LangChain.\n",
    "4. Insights into the strengths and limitations of zero-shot approaches.\n",
    "5. A foundation for further exploration and innovation in prompt engineering.\n",
    "\n",
    "This knowledge will empower learners to leverage AI models more effectively across a wide range of applications, enhancing their ability to solve novel problems and create more flexible AI systems."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Setup\n",
    "\n",
    "Let's start by importing the necessary libraries and setting up our environment."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "from langchain_openai import ChatOpenAI\n",
    "from langchain.prompts import PromptTemplate\n",
    "from langchain.chains import LLMChain\n",
    "from dotenv import load_dotenv\n",
    "\n",
    "# Load environment variables\n",
    "load_dotenv()\n",
    "\n",
    "# Set up OpenAI API key\n",
    "os.environ[\"OPENAI_API_KEY\"] = os.getenv('OPENAI_API_KEY')\n",
    "\n",
    "# Initialize the language model\n",
    "llm = ChatOpenAI(model=\"gpt-4o-mini\")\n",
    "\n",
    "\n",
    "def create_chain(prompt_template):\n",
    "    \"\"\"\n",
    "    Create a LangChain chain with the given prompt template.\n",
    "    \n",
    "    Args:\n",
    "        prompt_template (str): The prompt template string.\n",
    "    \n",
    "    Returns:\n",
    "        LLMChain: A LangChain chain object.\n",
    "    \"\"\"\n",
    "    prompt = PromptTemplate.from_template(prompt_template)\n",
    "    return prompt | llm"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1. Direct Task Specification\n",
    "\n",
    "In this section, we'll explore how to craft prompts that clearly define the task without providing examples. This is the essence of zero-shot prompting."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Text: I absolutely loved the movie! The acting was superb.\n",
      "Sentiment: Positive\n",
      "Text: The weather today is quite typical for this time of year.\n",
      "Sentiment: Neutral\n",
      "Text: I'm disappointed with the service I received at the restaurant.\n",
      "Sentiment: Negative\n"
     ]
    }
   ],
   "source": [
    "direct_task_prompt = \"\"\"Classify the sentiment of the following text as positive, negative, or neutral.\n",
    "Do not explain your reasoning, just provide the classification.\n",
    "\n",
    "Text: {text}\n",
    "\n",
    "Sentiment:\"\"\"\n",
    "\n",
    "direct_task_chain = create_chain(direct_task_prompt)\n",
    "\n",
    "# Test the direct task specification\n",
    "texts = [\n",
    "    \"I absolutely loved the movie! The acting was superb.\",\n",
    "    \"The weather today is quite typical for this time of year.\",\n",
    "    \"I'm disappointed with the service I received at the restaurant.\"\n",
    "]\n",
    "\n",
    "for text in texts:\n",
    "    result = direct_task_chain.invoke({\"text\": text}).content\n",
    "    print(f\"Text: {text}\")\n",
    "    print(f\"Sentiment: {result}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2. Format Specification\n",
    "\n",
    "Providing output format guidelines in the prompt can help structure the AI's response in a zero-shot scenario."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "**Headline:** Astronomers Unveil New Earth-Like Exoplanet in Habitable Zone\n",
      "\n",
      "**Lead:** In a groundbreaking discovery, a team of astronomers has identified a new Earth-like exoplanet located within the habitable zone of its star, raising hopes for the possibility of extraterrestrial life. Dubbed \"Kepler-452d,\" the planet orbits a sun-like star approximately 1,400 light-years away, offering a tantalizing glimpse into worlds beyond our solar system.\n",
      "\n",
      "**Body:** The discovery was made using advanced observational techniques from the Kepler Space Telescope, which has been instrumental in finding thousands of exoplanets. Kepler-452d is approximately 1.6 times the size of Earth and orbits its star at a distance that allows for liquid water to exist on its surface—a crucial condition for life as we know it. Scientists believe that the planet's atmosphere could potentially support life, making it a prime candidate for future exploration.\n",
      "\n",
      "The research team, led by Dr. Emily Chen, emphasizes the significance of this find. \"This is one of the most promising Earth-like planets we've discovered to date,\" Chen stated. \"The conditions appear to be suitable for life, and with the right tools, we may be able to analyze its atmosphere in the coming years.\" As technology advances, the prospect of studying Kepler-452d and others like it becomes increasingly viable.\n",
      "\n",
      "**Conclusion:** As we stand on the brink of a new era in space exploration, this exciting discovery fuels the quest to answer one of humanity's most profound questions: Are we alone in the universe?\n"
     ]
    }
   ],
   "source": [
    "format_spec_prompt = \"\"\"Generate a short news article about {topic}. \n",
    "Structure your response in the following format:\n",
    "\n",
    "Headline: [A catchy headline for the article]\n",
    "\n",
    "Lead: [A brief introductory paragraph summarizing the key points]\n",
    "\n",
    "Body: [2-3 short paragraphs providing more details]\n",
    "\n",
    "Conclusion: [A concluding sentence or call to action]\"\"\"\n",
    "\n",
    "format_spec_chain = create_chain(format_spec_prompt)\n",
    "\n",
    "# Test the format specification prompting\n",
    "topic = \"The discovery of a new earth-like exoplanet\"\n",
    "result = format_spec_chain.invoke({\"topic\": topic}).content\n",
    "print(result)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3. Multi-step Reasoning\n",
    "\n",
    "For complex tasks, we can break them down into simpler zero-shot steps. This approach can improve the overall performance of the model."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1. **Main Argument**: The primary claim of the text is that while electric vehicles (EVs) are often promoted as a solution to climate change, their environmental impact is complex and not entirely positive due to the mining for battery production and reliance on fossil fuels for electricity.\n",
      "\n",
      "2. **Supporting Evidence**: \n",
      "   - The production of batteries for electric vehicles involves significant mining operations, which can lead to habitat destruction.\n",
      "   - Mining for battery materials can also result in water pollution.\n",
      "   - The environmental benefits of electric vehicles may be undermined if the electricity used for charging is sourced from fossil fuels.\n",
      "   - Acknowledgment that improvements in renewable energy sources and battery technology could enhance the role of electric vehicles in addressing climate change in the future.\n",
      "\n",
      "3. **Potential Counterarguments**: \n",
      "   - Proponents of electric vehicles might argue that the overall lifecycle emissions of EVs are still lower than those of traditional vehicles, even when accounting for battery production and electricity sourcing.\n",
      "   - The advancements in battery recycling technologies could mitigate the negative environmental impacts associated with battery production.\n",
      "   - Renewable energy sources are rapidly growing, and the transition to green electricity could significantly improve the environmental benefits of electric vehicles.\n",
      "   - The argument could be made that the shift towards electric vehicles is a necessary step toward reducing reliance on fossil fuels, despite current limitations in technology and energy sourcing.\n"
     ]
    }
   ],
   "source": [
    "multi_step_prompt = \"\"\"Analyze the following text for its main argument, supporting evidence, and potential counterarguments. \n",
    "Provide your analysis in the following steps:\n",
    "\n",
    "1. Main Argument: Identify and state the primary claim or thesis.\n",
    "2. Supporting Evidence: List the key points or evidence used to support the main argument.\n",
    "3. Potential Counterarguments: Suggest possible objections or alternative viewpoints to the main argument.\n",
    "\n",
    "Text: {text}\n",
    "\n",
    "Analysis:\"\"\"\n",
    "\n",
    "multi_step_chain = create_chain(multi_step_prompt)\n",
    "\n",
    "# Test the multi-step reasoning approach\n",
    "text = \"\"\"While electric vehicles are often touted as a solution to climate change, their environmental impact is not as straightforward as it seems. \n",
    "The production of batteries for electric cars requires significant mining operations, which can lead to habitat destruction and water pollution. \n",
    "Moreover, if the electricity used to charge these vehicles comes from fossil fuel sources, the overall carbon footprint may not be significantly reduced. \n",
    "However, as renewable energy sources become more prevalent and battery technology improves, electric vehicles could indeed play a crucial role in combating climate change.\"\"\"\n",
    "\n",
    "result = multi_step_chain.invoke({\"text\": text}).content\n",
    "print(result)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4. Comparative Analysis\n",
    "\n",
    "Let's compare different zero-shot prompt structures for the same task to evaluate their effectiveness."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Task: Explain conciesly the concept of blockchain technology\n",
      "\n",
      "Basic Prompt Result:\n",
      "Blockchain technology is a decentralized digital ledger system that securely records transactions across multiple computers. It ensures that once data is entered, it cannot be altered without consensus from the network participants. Each block contains a list of transactions and a cryptographic hash of the previous block, forming a chain. This structure enhances security, transparency, and trust, as it eliminates the need for a central authority and makes tampering with data extremely difficult. Blockchain is widely used in cryptocurrencies, supply chain management, and various applications requiring secure and transparent record-keeping.\n",
      "\n",
      "--------------------------------------------------\n",
      "\n",
      "Structured Prompt Result:\n",
      "### 1. Definition\n",
      "Blockchain technology is a decentralized digital ledger system that records transactions across multiple computers in a way that ensures the security, transparency, and immutability of the data. Each transaction is grouped into a block and linked to the previous block, forming a chronological chain.\n",
      "\n",
      "### 2. Key Features\n",
      "- **Decentralization**: No single entity controls the network; all participants have access to the same data.\n",
      "- **Transparency**: Transactions are visible to all users, promoting accountability.\n",
      "- **Immutability**: Once recorded, transactions cannot be altered or deleted, ensuring data integrity.\n",
      "- **Security**: Cryptographic techniques protect data, making it resistant to fraud and hacking.\n",
      "- **Consensus Mechanisms**: Various protocols (e.g., Proof of Work, Proof of Stake) are used to validate transactions and maintain network integrity.\n",
      "\n",
      "### 3. Real-world Applications\n",
      "- **Cryptocurrencies**: Digital currencies like Bitcoin and Ethereum use blockchain for secure transactions.\n",
      "- **Supply Chain Management**: Enhances traceability and transparency in tracking goods from origin to destination.\n",
      "- **Smart Contracts**: Self-executing contracts with the terms directly written into code, automating processes without intermediaries.\n",
      "- **Voting Systems**: Secure and transparent voting solutions to enhance electoral integrity.\n",
      "- **Healthcare**: Secure sharing of patient data across platforms while maintaining privacy.\n",
      "\n",
      "### 4. Potential Impact on Industries\n",
      "- **Finance**: Reduces costs and increases transaction speeds by eliminating intermediaries, enabling faster cross-border payments.\n",
      "- **Real Estate**: Streamlines property transactions through transparent records and fractional ownership possibilities.\n",
      "- **Insurance**: Automates claims processing and fraud detection through smart contracts.\n",
      "- **Manufacturing**: Enhances quality control and accountability in the production process through improved supply chain visibility.\n",
      "- **Government**: Increases transparency in public records and reduces corruption through tamper-proof systems. \n",
      "\n",
      "Overall, blockchain technology has the potential to revolutionize various sectors by improving efficiency, transparency, and security.\n",
      "\n",
      "--------------------------------------------------\n",
      "\n"
     ]
    }
   ],
   "source": [
    "def compare_prompts(task, prompt_templates):\n",
    "    \"\"\"\n",
    "    Compare different prompt templates for the same task.\n",
    "    \n",
    "    Args:\n",
    "        task (str): The task description or input.\n",
    "        prompt_templates (dict): A dictionary of prompt templates with their names as keys.\n",
    "    \"\"\"\n",
    "    print(f\"Task: {task}\\n\")\n",
    "    for name, template in prompt_templates.items():\n",
    "        chain = create_chain(template)\n",
    "        result = chain.invoke({\"task\": task}).content\n",
    "        print(f\"{name} Prompt Result:\")\n",
    "        print(result)\n",
    "        print(\"\\n\" + \"-\"*50 + \"\\n\")\n",
    "\n",
    "task = \"Explain concisely the concept of blockchain technology\"\n",
    "\n",
    "prompt_templates = {\n",
    "    \"Basic\": \"Explain {task}.\",\n",
    "    \"Structured\": \"\"\"Explain {task} by addressing the following points:\n",
    "1. Definition\n",
    "2. Key features\n",
    "3. Real-world applications\n",
    "4. Potential impact on industries\"\"\"\n",
    "}\n",
    "\n",
    "compare_prompts(task, prompt_templates)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": ".venv",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
